package com.hao.tool.logview.runlog.websocket;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

import java.text.DateFormat;
import java.util.Date;

/**
 * description
 *
 * @author RuiHaoZ on hgits.cn
 * @date 2019/3/3 15:36
 */
public class LogFilter extends Filter<ILoggingEvent> {
    @Override
    public FilterReply decide(ILoggingEvent event) {

        StringBuilder exceptionStringBuilder = new StringBuilder();
        IThrowableProxy iThrowableProxy = event.getThrowableProxy();
        if (iThrowableProxy != null) {
            exceptionStringBuilder.append("<span class='excehtext'>")
                    .append(iThrowableProxy.getClassName())
                    .append(" ")
                    .append(iThrowableProxy.getMessage())
                    .append("</span></br>");
            for (int i = 0; i < iThrowableProxy.getStackTraceElementProxyArray().length; i++) {
                exceptionStringBuilder.append("<span class='excetext'>")
                        .append(iThrowableProxy.getStackTraceElementProxyArray()[i].toString())
                        .append("</span></br>");
            }
        }
        LogMessage loggerMessage = LogMessage.build();
        loggerMessage.setClassName(event.getLoggerName());
        loggerMessage.setMessage(event.getFormattedMessage());
        loggerMessage.setLevel(event.getLevel().levelStr);
        loggerMessage.setThreadName(event.getThreadName());
        loggerMessage.setLogTime(DateFormat.getDateTimeInstance().format(new Date(event.getTimeStamp())));
        loggerMessage.setExceptionStr(exceptionStringBuilder.toString());
        LogQueue.getInstance().push(loggerMessage);
        return FilterReply.ACCEPT;
    }
}
